'use strict';

const BaseService = require('../base');
const { OrderStatusEnum } = require('../../utils/enum');
const dayjs = require('dayjs');
/**
 * 生成订单号
 * @return {string}
 */
function generateOrderNo() {
    const now = dayjs();
    // 生成格式：年月日时分秒+4位随机数
    return 'RE' + now.format('YYYYMMDDHHmmss') + Math.floor(Math.random() * 10000).toString().padStart(4, '0');
}

class RechargeService extends BaseService {
    static get modelName() {
        return 'Common.Recharge';
    }
    /**
     * 创建订单
     * @param {Object} orderData - 订单数据
     * @return {Promise<*>}
     */
    async create(orderData) {
        const { ctx } = this;
        /**
         * 校验用户
         */
        if (!orderData.user_id) throw new Error('用户不存在');
        // 检查用户是否存在
        const user = await ctx.model.Business.User.findOne({
            where: {
                id: orderData.user_id
            }
        })
        if (!user) {
            throw new Error('用户不存在');
        }
        if (!user.status) {
            throw new Error('用户已禁用');
        }
        if (!orderData.amount) throw new Error('充值金额不能为空');
        // 1. 生成订单号
        const orderNo = generateOrderNo();
        // 2. 创建主订单
        const createData = {
            order_no: orderNo,
            user_id: orderData.user_id,
            payment_amount: orderData.amount,
            status: OrderStatusEnum.PENDING
        }
        // 3. 创建订单
        return  await ctx.model.Common.Recharge.create(createData);
    }
    /**
     * 申请退款
     * @param {Object} params - 参数
     * @return {Promise<boolean>}
     */
    async refund(params) {
      const { ctx } = this;
      const { id, refund_reason, is_admin = true } = params;

      // 查询订单
      const order = await this.ctx.model.Common.Recharge.findOne({
          where: { id }
      });
      if (!order) {
        throw new Error('订单不存在');
      }
      // 查询用户余额
      const user = await ctx.model.Business.User.findOne({
        where: {
          id: order.user_id
        }
      })
      if (!user) {
        throw new Error('用户不存在');
      }
      if (user.balance < order.payment_amount) {
        throw new Error('用户余额不足,无法退款');
      } 
      const transaction = await ctx.model.transaction();

      try {
          if (!order) {
              throw new Error('订单不存在');
          }
          // 判断订单状态
          if(!is_admin) {
              if (order.status !== OrderStatusEnum.PAID && order.status !== OrderStatusEnum.REFUNDED) {
                  throw new Error('只有未确认的订单才能申请退款');
              }
          }
          const refund_amount = params.refund_amount || order.payment_amount
          // const refund_amount = 0.01
          let refundForm = {
              status: OrderStatusEnum.REFUNDING,
              refund_time: new Date(),
              refund_reason,
              refund_amount
          }
          // 更新订单状态
          await order.update(refundForm, { transaction });

          await transaction.commit();

          return true;
      } catch (error) {
          await transaction.rollback();
          throw error;
      }
  }

  /**
   * 处理退款
   */
  async refundConfirm(data) {
      const { id, refund_remark } = data;

      // 查询订单
      const order = await this.ctx.model.Common.Recharge.findOne({
          where: { id }
      });

      if (!order) {
          throw new Error('充值订单不存在');
      }
        // 调用退款接口
      await this.ctx.service.payment.refund.processRefund({
        order_no: order.order_no,
        refund_remark,
        refund_amount:  order.payment_amount,
        payment_amount: order.payment_amount
      });

      // 创建事务处理退款
      await order.update({
        status: OrderStatusEnum.REFUNDING,
      });
    
      return true
  }

  /**
   * 获取列表时的关联查询
   */
  getListInclude() {
    return [{
      model: this.ctx.model.Business.User,
      as: 'user',
      attributes: ['id', 'nickname', 'phone']
    }];
  }

  /**
   * 获取分页时的关联查询
   */
  getPageInclude() {
    return [{
      model: this.ctx.model.Business.User,
      as: 'user',
      attributes: ['id', 'nickname', 'phone']
    }];
  }
}

module.exports = RechargeService;
